package com.xbongbong.paas.script.controller;

import com.alibaba.fastjson.JSON;
import com.xbongbong.paas.help.CommonHelp;
import com.xbongbong.paas.pojo.dto.ReturnCustomer2PublicAsyncDTO;
import com.xbongbong.paas.pojo.dto.ReturnCustomer2PublicDTO;
import com.xbongbong.paas.pojo.vo.ReturnCustomer2PublicVO;
import com.xbongbong.paas.service.CustomerRuleService;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.util.DateTimeUtil;
import com.xbongbong.paas.toolbox.util.StringUtil;
import com.xbongbong.paas.toolbox.wrap.XbbResponse;
import com.xbongbong.pro.config.ProBaseConfig;
import com.xbongbong.pro.constant.XbbProConstant;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.enums.CompanyConfigEnum;
import com.xbongbong.saas.model.CustomerRuleModel;
import com.xbongbong.sys.domain.entity.CompanyConfigEntity;
import com.xbongbong.sys.help.SysEnvHelp;
import com.xbongbong.sys.model.CompanyConfigModel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Lazy;
import org.springframework.http.MediaType;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @author chy
 * @ProjectName xbb-web-script
 * @Description: 公海池规则相关数据接口
 * @date 2019/1/24 15:34
 */
@RestController
@RequestMapping(XbbProConstant.API_ROOT_PREFIX + "/script/customerPublicRule")
public class CustomerRuleScriptController {
    private static final Logger LOG = LoggerFactory.getLogger(CustomerRuleScriptController.class);
    @Lazy
    @Resource
    private CustomerRuleService customerRuleService;
    @Resource
    private CustomerRuleModel customerRuleModel;
    @Resource
    private CommonHelp commonHelp;
    @Resource
    private CompanyConfigModel companyConfigModel;
    @Resource
    private SysEnvHelp sysEnvHelp;
    @Resource
    private ProBaseConfig proBaseConfig;
    /**
     * 公海规则脚本
     * @param returnCustomer2PublicDTO
     * @param br
     * @return
     * 创建时间 2019/3/19 4:47 PM
     * 修改时间 2019/3/19 4:47 PM
     * @author chy
     * @since v1.0
     * @version v1.0
     */
    @RequestMapping(value = "/returnCustomer2Public", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String returnCustomer2Public(@Valid ReturnCustomer2PublicDTO returnCustomer2PublicDTO, BindingResult br) {
        XbbResponse<ReturnCustomer2PublicVO> response;
        try {
            response = returnCustomer2Public(returnCustomer2PublicDTO);
        } catch (XbbException e) {
            response = new XbbResponse<>(e);
        }
        return JSON.toJSONString(response);
    }

    public XbbResponse<ReturnCustomer2PublicVO> returnCustomer2Public(ReturnCustomer2PublicDTO returnCustomer2PublicDTO) throws XbbException {
        ReturnCustomer2PublicVO returnCustomer2PublicVO = new ReturnCustomer2PublicVO();
        String key = returnCustomer2PublicDTO.getKey();
        if (!proBaseConfig.getXbbCode().equals(key)) {
            LOG.error("公海客户规则校验 密码错误，停止定时任务！");
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100066);
        }
        if (!Objects.equals(returnCustomer2PublicDTO.getNotify(), 1)
                && !Objects.equals(returnCustomer2PublicDTO.getNotify(), 0)
                && returnCustomer2PublicDTO.getNotify() != null) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100015, "notify只能为0和1，0：不提醒 1：提醒");
        }
        if (!Objects.equals(returnCustomer2PublicDTO.getBack(), 1)
                && !Objects.equals(returnCustomer2PublicDTO.getBack(), 0)
                && returnCustomer2PublicDTO.getBack() != null) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100015, "back只能为0和1，0：不退回 1：退回");
        }
        Boolean notify = Objects.equals(returnCustomer2PublicDTO.getNotify(), 1);
        Boolean back = Objects.equals(returnCustomer2PublicDTO.getBack(), 1);
        String corpid = returnCustomer2PublicDTO.getCorpid();
        if (!notify && !back) {
            LOG.warn("既不需要消息提醒又不用退回公海池规则没有执行必要，停止定时任务！");
            return new XbbResponse<>(returnCustomer2PublicVO);
        }
        if (StringUtil.isNotEmpty(corpid)) {
            if (commonHelp.isCustomerPublicPoolSeniorModel(corpid)){
                LOG.warn("该公司开启了客户公海高级模式，停止定时任务！");
                return new XbbResponse<>(returnCustomer2PublicVO);
            }
            ReturnCustomer2PublicAsyncDTO returnCustomer2PublicAsyncDTO = new ReturnCustomer2PublicAsyncDTO();
            returnCustomer2PublicAsyncDTO.setNotify(notify);
            returnCustomer2PublicAsyncDTO.setBack(back);
            returnCustomer2PublicAsyncDTO.setCorpid(corpid);
            customerRuleService.returnCustomer2PublicAsync(returnCustomer2PublicAsyncDTO);
        } else {
            if (sysEnvHelp.isGrayEnvironment()) {
                /*************************灰度逻辑开始*************************/
                //获取灰度公司列表
                CompanyConfigEntity companyConfig = companyConfigModel.getByConfigAlias(CompanyConfigEnum.GRAY_CORPID_LIST.getAlias(), "0");
                List<String> grayCorpids = companyConfig != null ? JSON.parseArray(companyConfig.getConfigValue(), String.class) : new ArrayList<>();
                if (CollectionsUtil.isNotEmpty(grayCorpids)) {
                    for (String singleCorpid : grayCorpids) {
                        ReturnCustomer2PublicAsyncDTO returnCustomer2PublicAsyncDTO = new ReturnCustomer2PublicAsyncDTO();
                        returnCustomer2PublicAsyncDTO.setNotify(notify);
                        returnCustomer2PublicAsyncDTO.setBack(back);
                        returnCustomer2PublicAsyncDTO.setCorpid(singleCorpid);
                        customerRuleService.returnCustomer2PublicAsync(returnCustomer2PublicAsyncDTO);
                    }
                }
                /*************************灰度逻辑结束*************************/
            } else {
                /*************************非灰度逻辑开始*************************/
                Long now = DateTimeUtil.getInt();
                // 每次查询的最大公司数
                Integer pageSize = 100;
                String startCorpid = null;
                List<String> corpids = customerRuleModel.findCorps(now,startCorpid, pageSize);
                //灰度环境没有专门配置公海池标准模式脚本，所以需要灰度公司走非灰度逻辑
                //CompanyConfigEntity companyConfig = companyConfigModel.getByConfigAlias(CompanyConfigEnum.GRAY_CORPID_LIST.getAlias(), "0");
                //List<String> grayCorpids = companyConfig != null ? JSON.parseArray(companyConfig.getConfigValue(), String.class) : new ArrayList<>();
                while (CollectionsUtil.isNotEmpty(corpids)) {
                    //去除灰度公司
                    //corpids.removeIf(grayCorpids::contains);
                    for (String singleCorpid : corpids) {
                        ReturnCustomer2PublicAsyncDTO returnCustomer2PublicAsyncDTO = new ReturnCustomer2PublicAsyncDTO();
                        returnCustomer2PublicAsyncDTO.setNotify(notify);
                        returnCustomer2PublicAsyncDTO.setBack(back);
                        returnCustomer2PublicAsyncDTO.setCorpid(singleCorpid);
                        customerRuleService.returnCustomer2PublicAsync(returnCustomer2PublicAsyncDTO);
                    }
                    startCorpid = corpids.get(corpids.size() - 1);
                    corpids = customerRuleModel.findCorps(now,startCorpid, pageSize);
                }
                /*************************非灰度逻辑结束*************************/
            }
        }
        return new XbbResponse<>(returnCustomer2PublicVO);
    }
}
